package com.freesky.biz.icbc.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.freesky.biz.icbc.domain.TIcbcWarmWinter;
import com.freesky.biz.icbc.domain.TScanBusi;
import com.freesky.biz.icbc.domain.TScanUser;
import com.freesky.biz.icbc.excel.TPensionUserImport;
import com.freesky.biz.icbc.excel.TScanUserExport;
import com.freesky.biz.icbc.excel.TScanUserImport;
import com.freesky.biz.icbc.mapper.ScanBusiMapper;
import com.freesky.biz.icbc.mapper.ScanChannelMapper;
import com.freesky.biz.icbc.mapper.ScanUserMapper;
import com.freesky.biz.icbc.service.IIcbcWarmWinterService;
import com.freesky.biz.icbc.service.IScanUserService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.constant.HttpStatus;
import com.freesky.common.constant.UserConstants;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.core.domain.entity.TScanChannel;
import com.freesky.common.enums.ExportStatusEnum;
import com.freesky.common.exception.CustomException;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.poi.ExcelUtil;
import com.freesky.system.domain.SysPost;
import com.freesky.system.domain.TExportRecord;
import com.freesky.system.domain.TImportRecord;
import com.freesky.system.service.ITExportRecordService;
import com.freesky.system.service.ITImportRecordService;
import com.freesky.system.task.SyncReport;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ScanUserServiceImpl implements IScanUserService {

    @Autowired
    private ScanUserMapper scanUserMapper;

    @Autowired
    private ScanChannelMapper scanChannelMapper;


    @Autowired
    private ScanBusiMapper scanBusiMapper;

    @Autowired
    private ITExportRecordService exportRecordService;

    @Autowired
    private ITImportRecordService importRecordService;

    @Autowired
    private SyncReport syncReport;


    @Override
    public int insertScanUser(TScanUser scanUser) {
        return scanUserMapper.insertScanUser(scanUser);
    }

    @Override
    public int updateScanUser(TScanUser scanUser) {
        return scanUserMapper.updateScanUser(scanUser);
    }

    @Override
    public List<TScanUser> selectScanUserList(TScanUser scanUser) {
        return scanUserMapper.selectScanUserList(scanUser);
    }

    @Override
    public boolean checkMobileUnique(TScanUser scanUser) {
        TScanUser scanUser2 = scanUserMapper.checkMobileUnique(scanUser.getMobile());
        if (StringUtils.isNotNull(scanUser2) && !scanUser2.getScanUserId().equalsIgnoreCase(scanUser.getScanUserId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int deleteScanUserById(Long[] scanUserIds) {
        return scanUserMapper.deleteScanUserById(scanUserIds);
    }

    @Override
    public TScanUser selectScanUserById(Long scanUserId) {
        return scanUserMapper.selectScanUserById(scanUserId);
    }

    @Override
    public List<TScanUserExport> exportScanUserList(TScanUser scanUser) {
        List<TScanUserExport> scanUserExportList = scanUserMapper.exportScanUserList(scanUser);
        TScanBusi scanBusi = new TScanBusi();
        List<TScanBusi> scanBusiList = scanBusiMapper.selectScanBusiList(scanBusi);
        Map<String,TScanBusi> scanBusiMap = scanBusiList.stream().collect(Collectors.toMap(TScanBusi::getBusiCode,Function.identity(), (key1, key2) -> key2));
        for(int i=0;i<scanUserExportList.size();i++){
            TScanUserExport scanUserExport = scanUserExportList.get(i);

            if("1".equalsIgnoreCase(scanUserExport.getDataScope())){
                scanUserExport.setDataScope("查看所有数据");
            } else if("2".equalsIgnoreCase(scanUserExport.getDataScope())){
                scanUserExport.setDataScope("查看分行及以下数据");
            } else if("3".equalsIgnoreCase(scanUserExport.getDataScope())){
                scanUserExport.setDataScope("查看支行及以下数据");
            } else if("4".equalsIgnoreCase(scanUserExport.getDataScope())){
                scanUserExport.setDataScope("查看网点的数据");
            } else if("5".equalsIgnoreCase(scanUserExport.getDataScope())){
                scanUserExport.setDataScope("查看本人数据");
            }

            if("1".equalsIgnoreCase(scanUserExport.getGrantType())){
                scanUserExport.setGrantType("二维码");
            } else {
                scanUserExport.setGrantType("无权限");
            }

            if(StringUtils.isEmpty(scanUserExport.getBusiCode())){
                continue;
            }
            int nLoop = 0;
            StringBuffer busiNameBuffer = new StringBuffer();
            String []arrBusiCode = scanUserExport.getBusiCode().split(",");
            for(int j=0;j<arrBusiCode.length;j++){
                String busiCode  = arrBusiCode[j];
                TScanBusi scanBusiData = (TScanBusi) scanBusiMap.get(busiCode);
                if(scanBusiData!=null) {
                    if(nLoop>0) {
                        busiNameBuffer.append(",");
                    }
                    nLoop = nLoop + 1;
                    busiNameBuffer.append(scanBusiData.getName());
                }
            }
            scanUserExport.setBusiName(busiNameBuffer.toString());
            scanUserExportList.set(i,scanUserExport);
        }
        return scanUserExportList;
    }

    @Override
    public AjaxResult exportFile(TScanUser scanUser) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        TExportRecord exportRecord = new TExportRecord();
        exportRecord.setId(SeqUtil.getSeqId());
        exportRecord.setBizType("SCAN_USER");
        exportRecord.setCreateBy(String.valueOf(sysUser.getUserId()));

        TExportRecord exportRecordSelect = exportRecordService.selectRecordExportByStatus(exportRecord);
        if (exportRecordSelect != null) {
            return AjaxResult.error("已经有下载任务");
        }

        exportRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());
        System.out.println(JSON.toJSONString(exportRecord));
        exportRecordService.insert(exportRecord);

        syncReport.exportFileMutilHeader(scanUser, new TScanUserExport(), IScanUserService.class,
                "exportScanUserList", "客户经理",Long.parseLong(exportRecord.getId()),sysUser.getUserName());

        return AjaxResult.success();
    }

    @Override
    public AjaxResult importExcel(MultipartFile file){
        try {
            TImportRecord importRecord = new TImportRecord();
            String batchId = SeqUtil.getSeqId();
            importRecord.setRecordId(batchId);

            List<TScanUserImport> updateList = new ArrayList<>();
            List<TScanUserImport> addList = new ArrayList<>();
            List<TScanUserImport> excelList = EasyExcel.read(file.getInputStream()).head(TScanUserImport.class).sheet().doReadSync();
            if(excelList==null || excelList.isEmpty()){
                throw new CustomException("Excel表格为空或解析失败");
            }

            TScanBusi scanBusi = new TScanBusi();
            List<TScanBusi> scanBusiList = scanBusiMapper.selectScanBusiList(scanBusi);
            Map<String,TScanBusi> scanBusiMap = scanBusiList.stream().collect(Collectors.toMap(TScanBusi::getBusiCode,Function.identity(), (key1, key2) -> key2));

            List<TScanUserImport> errorList = new ArrayList<>();
            for(int i=0;i<excelList.size();i++){
                TScanUserImport scanUserImport = excelList.get(i);
                scanUserImport.setId(SeqUtil.getSeqId());
                scanUserImport.setGrantType("1");
                if(StringUtils.isEmpty(scanUserImport.getName())){
                    scanUserImport.setRemarks("客户经理不能为空");
                    errorList.add(scanUserImport);
                    continue;
                }

                if(StringUtils.isEmpty(scanUserImport.getMobile())){
                    scanUserImport.setRemarks("客户经理不能为空");
                    errorList.add(scanUserImport);
                    continue;
                }

                if(StringUtils.isEmpty(scanUserImport.getBusiCode())){
                    scanUserImport.setRemarks("业务编码不能为空");
                    errorList.add(scanUserImport);
                    continue;
                }

                if(StringUtils.isEmpty(scanUserImport.getCodeBank1())){
                    scanUserImport.setRemarks("渠道号不能为空");
                    errorList.add(scanUserImport);
                    continue;
                }

                //数据权限：1、查看所有数据，2、查看分行及以下数据，3、查看支行及以下数据，4、查看网点的数据，5、查看本人数据
                if("查看所有数据".equalsIgnoreCase(scanUserImport.getDataScope())){
                    scanUserImport.setDataScope("1");
                } else if("查看分行及以下数据".equalsIgnoreCase(scanUserImport.getDataScope())){
                    scanUserImport.setDataScope("2");
                } else if("查看支行及以下数据".equalsIgnoreCase(scanUserImport.getDataScope())){
                    scanUserImport.setDataScope("3");
                } else if("查看网点的数据".equalsIgnoreCase(scanUserImport.getDataScope())){
                    scanUserImport.setDataScope("4");
                } else if("查看本人数据".equalsIgnoreCase(scanUserImport.getDataScope())){
                    scanUserImport.setDataScope("5");
                } else {
                    scanUserImport.setRemarks("数据权限不对，只能填：查看所有数据、查看分行及以下数据、查看支行及以下数据、查看网点的数据、查看本人数据");
                    errorList.add(scanUserImport);
                    continue;
                }

                if(scanBusiMap==null || !scanBusiMap.containsKey(scanUserImport.getBusiCode())){
                    scanUserImport.setRemarks("业务编码对应业务不存在");
                    errorList.add(scanUserImport);
                    continue;
                }

                TScanChannel scanChannel = scanChannelMapper.selectScanChannelByOutletNo(scanUserImport.getCodeBank1());
                if(scanChannel==null){
                    scanUserImport.setRemarks("渠道不存在");
                    errorList.add(scanUserImport);
                    continue;
                }
                scanUserImport.setChannelId(String.valueOf(scanChannel.getChannelId()));

                TScanUser scanUser = scanUserMapper.checkMobileUnique(scanUserImport.getMobile());
                if(scanUser!=null){
                    scanUserImport.setId(scanUser.getScanUserId());
                    if(StringUtils.isNotEmpty(scanUser.getBusiCode())){
                        if(scanUser.getBusiCode().indexOf(scanUserImport.getBusiCode())>=0){
                            scanUserImport.setBusiCode(scanUser.getBusiCode());
                        } else {
                            scanUserImport.setBusiCode(scanUser.getBusiCode() + "," + scanUserImport.getBusiCode());
                        }
                    }
                    updateList.add(scanUserImport);
                } else {
                    scanUserImport.setId(SeqUtil.getSeqId());
                    addList.add(scanUserImport);
                }
            }
            importRecord.setBizType("SCAN_USER");
            importRecord.setTotalRecord(Long.valueOf(excelList.size()));
            importRecord.setErrorRecord(Long.valueOf(errorList.size()));
            importRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());

            if(errorList.size()>0){
                ExcelUtil util = new ExcelUtil(TScanUserImport.class);
                importRecord.setStatus(ExportStatusEnum.SUBMIT_FAIL.getValue());
                AjaxResult result = util.exportEasyExcel(errorList, "导入用户-error");
                if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)) {
                    String exFileName = (String) result.get(AjaxResult.MSG_TAG);
                    // 异常文件名
                    importRecord.setExFileName(exFileName);
                    importRecord.setStatus(2L);
                }
                importRecordService.insertTImportRecord(file,importRecord);
                return result;
            } else {
                if(addList.size()>0) {
                    scanUserMapper.batchAddList(addList);
                }

                if(updateList.size()>0){
                    scanUserMapper.batchUpdateList(updateList);
                }
                importRecord.setStatus(ExportStatusEnum.SUBMIT_SUCCESS.getValue());
                importRecordService.insertTImportRecord(file,importRecord);
            }

        } catch (Exception ioe){
            throw new CustomException("解析Excel时发生错误", ioe);
        }
        return AjaxResult.success();
    }
}
